package com.topsoft.email.util.mail;

import java.io.File;

import com.mvc.core.utils.StringUtils;
import com.topsoft.email.util.bean.AttachFile;
import com.topsoft.email.util.bean.MailParamBean;
import com.topsoft.email.util.enums.MailType;

import jodd.mail.Email;
import jodd.mail.EmailAttachment;
import jodd.mail.SendMailSession;
import jodd.mail.SmtpServer;
import jodd.mail.SmtpSslServer;
import jodd.mail.att.FileAttachment;


public class JoddMailSender {


	
	/**
	 * 发送邮件
	 * @param paramBean
	 */
	public static boolean sendMail(MailParamBean paramBean){
		
		try {
			
			String[] emails = paramBean.getReceiver().split(StringUtils.COMMA);
			
            //邮件主体
			Email email = Email.create().from(paramBean.getSmtpUserName())
					.subject(paramBean.getTitle())// 设置了主题
					.to(emails);

			if (MailType.TEXT == paramBean.getMailType()) {
				email.addText(paramBean.getContent());
			} else {
				email.addHtml(paramBean.getContent());
			}
			
			//添加附件
			if(null!=paramBean.getAttachFileList()){
				for(AttachFile file : paramBean.getAttachFileList()){
					EmailAttachment attachment = new FileAttachment(new File(file.getAttachFileUrl()),
							                                        file.getAttachFileName(),
							                                        file.getAttachType());
					email.attach(attachment);
				}
			}
			

			// 创建session
			SmtpServer<?> smtp = SmtpSslServer.create(paramBean.getHost(), paramBean.getPort());// 设置SSL的smtp服务器，我的，smtp.mxhichina.com
			smtp.authenticateWith(paramBean.getSmtpUserName(), paramBean.getSmtpPassword());// 我的,service@www.dtxzw.com,密码省略....
			SendMailSession session = smtp.createSession();

			session.open();// 打开连接
			session.sendMail(email);// 发送邮件
			session.close();// 关闭连接
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static void main(String[] args) {
		MailParamBean paramBean=new MailParamBean();
		paramBean.setMailUserId("1");
		paramBean.setReceiver("243860327@qq.com");
		paramBean.setTitle("你好吗");
		paramBean.setMailType(MailType.HTML);
		paramBean.setContent("<h1>你好吗</h1>");
		
		
		paramBean.setSmtpUserName("guokaige@topnet.net.cn");
		paramBean.setSmtpPassword("Bss5224271");
		paramBean.setHost("465");
		paramBean.setProtocol("smtp");
		paramBean.setHost("smtp.exmail.qq.com");
		
		
		
		System.out.println(JoddMailSender.sendMail(paramBean));
		
		
		
	}

}